'use strict'

const titbit = require('titbit')
const {httpcli} = require('gohttp')

//let cert_path = `/usr/local/cert`

let cert_path = `${process.env.HOME}/source`

const app = new titbit({
  useLimit: true,
  maxConn: 50,
  maxIPRequest: 15,
  unitTime: 5,
  cert : `${cert_path}/www.w3xm.cn.crt`,
  key : `${cert_path}/www.w3xm.cn.key`,
})

app.pre(async (c, next) => {

  if (c.query.passkey === undefined || c.query.passkey !== 'daojian-token-9009') {
    return c.send('ok')
  }

  await next()
})

function tokenUrl(appid, secret) {
  return 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'
          + `&appid=${appid}&secret=${secret}`;
}

app.get('/gzh/:appid/:secret', async c => {

  let r = await httpcli.get( tokenUrl(c.param.appid, c.param.secret) )

  if (!r.ok) {
    return c.status(500).send('failed')
  }

  let ret = r.json()

  if (ret.access_token) {
    return c.send(ret.access_token)
  }

  c.status(400).send(r.text())

})

app.run(1111)
